'''
This script will take pcap format files and compare the data portion
inside the udp packets.
By doing this it'll be easier to analyze the actual data inside the system.
'''

'''
Just a reminder: PCAP headers

Global header:
    guint32 magic_number
    guint16 version_major
    guint16 version_minor
    guint32 thiszone
    guint32 sigfigs
    guint32 snaplen
    guint32 network

Packet header:
    guint32 ts_sec
    guint32 ts_usec
    guint32 incl_len
    guint32 orig_len
'''

import sys
import struct

def main(args):
    fl = open(args[0], 'r')

    global_header = fl.read(24)

    reverse = False
    if "\xd4\xc3\xb2\xa1" in global_header[:4]:
        reverse = True

    #Skip rest of the global header
    fl.seek(24)

    data1 = ""
    data2 = ""

    bold = "\033[1m"
    reset = "\033[0;0m"

    while True:
        data2 = data1
        
        packet_header = fl.read(16)

        if len(packet_header)!=16: break

        if reverse:
            packet_header = (packet_header[0:4][::-1]+
                             packet_header[4:8][::-1]+
                             packet_header[8:12][::-1]+
                             packet_header[12:16][::-1])

        packet_len = struct.unpack('>I', packet_header[8:12])[0]

        data1 = fl.read(packet_len)

        #To make sure that the packet contains udp segment
        if data1[23]=="\x11":

            data1 = data1[42:]

            print "New packet: data_len=={}".format(len(data1))
            print ' '.join([data1[x].encode("hex")
                            for x in range(0, len(data1))])

            if data2!="":
                print ("\nDifferences between previous "+
                      "packet: data_len=={}".format(len(data2)))

                difference = []
                for i in range(0,min([len(data2),len(data1)])):
                    if data1[i]!=data2[i]:
                        difference.append(data2[i].encode("hex"))
                    else:
                        difference.append(bold+"XX"+reset)

                print ' '.join(difference)
                print "\n\n"

            else: print "\n\n\n"
        
                

if __name__=="__main__":
    if len(sys.argv)>1:
        main(sys.argv[1:])
    else:
        print "No command line arguments given."
